// pages/tabbar/shopStore/shopStore.js
import regeneratorRuntime from '../../../utils/runtime.js';
import img_list from '../../../utils/util.js';
import { setTabBar,setTabList,jsonParamToQueryStr } from '../../../utils/util'
import { getData, setData, clearData, removeData, dataKey } from '../../../utils/storage.js';
import shareFun from '../../../utils/shareFun.js';
import clipboard from '../../../utils/clipboard.js';
import {
  search,
  refreshInfo,
  saveRecord,
  pindao,
  pddPindao,
  recommend,
  getListRecommend,
  getUserData,
  login,
  getBanner,
  approve_mode,
  item_select,
  getLiveList,
  paramGet,
  getVideoGifUrl,
  checkHostReg
} from '../../../utils/imapi.js';

var log = require('../../../utils/log.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   * 
   */
  data: {
	chain:false,  //是否弹出转链的弹框
	In:true,
	cur_scroll_top: 0,
    tabs: [],
    is_load: false,
    show: 1,
    cur_index: 0,
    is_show_active: 0,
    currentIndicator: 0,
    tabIndex: 0,
    show_title: true,
    color: "#ff4158",
    competitive_text: 'competitiveA',
    size: 40,
    wsize: 720,
    tabCur1: 0,
	GongGe:[  //九宫格
	    {image:'../../../images/tabbar/index_1.png',name:'一元购物'},
		// {image:'../../../images/tabbar/index_1.png',name:'超级红包',url:'/packageTab/pages/envelope/envelope'},
		{image:'../../../images/tabbar/index_2.png',name:'百亿补贴',url:'/packageTab/pages/subsidies/subsidies'},
		{image:'../../../images/tabbar/index_3.png',name:'品牌秒杀',url:'/packageTab/pages/Secondskill/Secondskill'},
		{image:'../../../images/tabbar/index_4.png',name:'手机充值', url: '/packageTab/pages/phone/phone'},
		{image:'../../../images/tabbar/index_5.png',name:'主播申请', url: '/pages/module/hostApply/hostApply' },
		{image:'../../../images/tabbar/index_6.png',name:'美团红包', url: '/packageTab/pages/meituan/meituan' },
		{image:'../../../images/tabbar/index_7.png',name:'饿了么', url: '/packageTab/pages/hungry/hungry'},
		{image:'../../../images/tabbar/index_8.png',name:'团油特惠', url: '/packageTab/pages/group/group'},
		{image:'../../../images/tabbar/index_9.png',name:'特价影院', url: '/packageTab/pages/movie/movie'},
		{image:'../../../images/tabbar/index_10.png',name:'车票购买',url: '/packageTab/pages/ticket/ticket'},
		{image:'../../../images/tabbar/oc0ab-pyv18.gif',name:'主会场',url: '/packageTab/pages/MainCourse/MainCourse'}
	],
	slideWidth: '',
	slideLeft: '',
    data: {
      add_cart_num: 2,
      carousel: [
        // {image:'/images/index/banner.png'},
        // {image:'/images/index/banner.png'},
      ],
      activity_enter: [
        { id: '1', image: '/images/index/b_icon1.png', is_show_red: false, show_text: '成长值', name: '成长值', url: '/pages/module/growth/growth' },
        { id: '2', image: '/images/index/b_icon2.png', name: '播主申请', is_show_red: true, show_text: '播主申请', url: '/pages/module/hostApply/hostApply' },
        { id: '3', image: '/images/index/b_icon3.png', name: '1元购', is_show_red: false, show_text: '1元购', url: '/images/index/b_icon2.png' },
		{ id: '4', image: '/images/index/b_icon4.png', name: '美团红包', is_show_red: false, show_text: '美团红包', url: '/packageTab/pages/meituan/meituan?custom=美团红包&img=https://img.xingkonglian.net/img/activity/mthb.png' },
    { id: '5', image: '/images/index/b_icon5.png', name: '饿了么', is_show_red: false, show_text: '饿了么', url: '/packageTab/pages/hungry/hungry' },
    { id: '6', image: '/images/index/tuanyou.png', name: '加油吧', is_show_red: false, show_text: '加油吧', url: '/packageTab/pages/group/group' },
	{ id: '7', image: '/images/index/DY1.png', name: '电影票', is_show_red: false, show_text: '电影票', url: '/packageTab/pages/movie/movie' }
      ],
      liveList: [], //短视频数据png
      liveDataList:[], // 直播数据
      productList: [],
      tabData1: [],
    },
    showMenu: 0,
    is_show_big: 0,
    items: [
      { name: '蓝', value: '#3F82FD', checked: 'true' },
      { name: '红', value: '#ff4158' },
    ],
    select_list: [
      { select_img: '/images/index/mother.png', select_text: '我是宝妈', is_select: 1, status: 'BM' },
      { select_img: '/images/index/student.png', select_text: '我是学生', is_select: 0, status: 'STU' },
      { select_img: '/images/index/job.png', select_text: '我是职场人士', is_select: 0, status: 'WORKER' },
    ],
    choose_btn_list: [
      { name: "拼多多", img: "/images/index/PDD.png", p: 'PDD', id: 1 },
      { name: "唯品会", img: "/images/index/VIP.png", p: 'VIP', id: 2 },
      { name: "京东", img: "/images/index/JD.png", p: 'JD', id: 3 },
      { name: "淘宝", img: "/images/index/TB.png", p: 'TB', id: 4 },
    ],
    img_list: {}, // 网络图标
    options:{},
	background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    indicatorDots: true,
	vertical: false,
	autoplay: false,
	interval: 2000,
	duration: 500,
	detail:1,
  hot_items:[],
  is_audit:true, // 是否审核状态
  getClip:'',  //复制的内容
  guide:0,  //指引的显示
  guide_idx:[], //指引的图片
  guide_top:[],
  },
  onLoad: async function (options) {


    // test for  finder
   // let p= encodeURIComponent('share_uid=1')
    //options.scene=p

    this.setData({
      img_list: img_list.img_list,
      options:options,
    })

    console.log('===index options:',options)

    log.info('===index options:',options)

    this.load_approve_mod()


    // 用户无关的异步数据调用接口
    console.log("请求 getShortLiveData()....")
    this.getShortLiveData() // 获得短视频数据



    console.log(options)
    var sence = options.scene || ''
    app.globalData.sence = sence;
    var that = this;
    this.need_home = true;
    this.is_first_open = true;
  
    this.data.tabData2 = this.data.tabData1 = [
      // {name:"为你推荐",id:'23',productList:[],pro_page:1,isAll:false,p:'JD'},
      { name: "为你推荐", id: '23', productList: [], pro_page: 1, isAll: false, p: 'RE' },
      { name: "今日爆款", id: '1', productList: [], pro_page: 1, isAll: false, p: 'PDD' },
      { name: "品牌清仓", id: '2', productList: [], pro_page: 1, isAll: false, p: 'PDD' },
      // {name:"热销爆品",id:'22',productList:[],pro_page:1,isAll:false,p:'JD'},
      { name: "秒杀", id: '33', productList: [], pro_page: 1, isAll: false, p: 'JD' },
      { name: "9.9专场", id: '10', productList: [], pro_page: 1, isAll: true, p: 'JD' },

      // {name:"超市",id:'25',productList:[],pro_page:1,isAll:true},
      // {name:"母婴",id:'26',productList:[],pro_page:1,isAll:true},
      // {name:"玩具",id:'26',productList:[],pro_page:1,isAll:true},
      // {name:"家具",id:'27',productList:[],pro_page:1,isAll:true},
      // {name:"日用",id:'27',productList:[],pro_page:1,isAll:true},
      // {name:"美妆",id:'28',productList:[],pro_page:1,isAll:true},
      // {name:"穿搭",id:'28',productList:[],pro_page:1,isAll:true},
    ]
    console.log(this.data.tabData2)
    this.setData({
      tabData2: this.data.tabData2
    })


    // updateby finder 20200807
    if (this.is_first_open) {
      //this.is_first_open = false;
      console.log("第一次打开 " + this.is_first_open)
      this.getBanner();
    }

    const Hot=await item_select({biz_code:'BP'});
    console.log(Hot);
    this.setData({
      hot_items:Hot.data
    })
    console.log(this.data.hot_items);


    app.sceneProcess(options) //场景处理
    // this.homepageguide(); 放在这里会在 token 过期 情况下 弹出异常
   //  wx.getClipboardData({
   //     success (res){
   //       console.log(res.data)
		 // this.setData({
			//  getClip:res.data
		 // })
   //     }
   //  })
    console.log(this.data.liveDataList)
  },
  closeIn(){
	  this.setData({
		  In:false
	  });
  },
  async closeGuide(e){
	  console.log(e);
    var id=e.currentTarget.dataset.id;
    
    this.setData({
	  	guide:0
	  });

	  let tip_banner=await saveRecord({ user_id: app.globalData.userInfo.uid, adv_id:id});
	  console.log(tip_banner);
	 
  },
  promote(){
	  wx.navigateTo({
	    url: '/pages/module/promote/promote'
	  })
  },
  onPageScroll: function (e) {
    var that = this;
    this.scrollTop = e.scrollTop
    if (e.scrollTop >= this.data.menuTop) {
      if (e.scrollTop > this.data.menuTop && this.data.menuFixed) return;
      that.setData({
        is_scroll: true,
        menuFixed: true
      })
    } else {
      that.setData({
        menuFixed: false,
        is_scroll: false,
        cur_scroll_top: e.scrollTop
      })
    }
  },
  onShow: async function () {
    setTabBar.call(this, 0)
    console.log('====index.onShow: print options:',this.data.options)
   

    if(JSON.stringify(app.globalData.configs)==="{}"){ //保证配置要正确
      this.loadConfigs()
    }else{
      this.calTgCount()
    }

    
    if(app.is_auth()){
      log.info('===正在使用小程序 uid: '+app.globalData.userInfo.uid+' nickname:'+app.globalData.userInfo.wx_nickname)
    }else{
     
    }

   

    var that = this;
    let userInfo, uid, token
    try {
      uid = await getData(dataKey.uid);
      app.globalData.uid = uid;
      token = await getData(dataKey.token);
      //app.globalData.token = token;
      wx.setStorageSync('token', token)
      userInfo = await getData(dataKey.userInfo);
      app.globalData.userInfo = userInfo;
    } catch (error) {

    }

    that.clipboardProcess(); //剪切板处理
   
    if (uid) {
      if (!this.need_home) return;
      this.need_home = false;
      this.setData({
        tabCur1: 0,
      })
      this.home();
      return;
    } else {




      
      wx.login({
        success: async ({ code }) => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          const rdata = await login(code);
          if (rdata.code == '0') {
            await setData(dataKey.token, rdata.data.access_token);
            uid = rdata.data.uid
            //app.globalData.token = rdata.data.access_token
            wx.setStorageSync('token', rdata.data.access_token)
            await setData(dataKey.session_key, rdata.data.session_key);
            app.globalData.session_key = rdata.data.session_key

            
          
            if (uid) {
              await setData(dataKey.uid, rdata.data.uid);
              await setData(dataKey.userInfo, rdata.data)
              app.globalData.userInfo = rdata.data;
              app.globalData.uid = uid;
             
             
              that.setData({
                showMenu: (rdata.data.identity_status) ? 0 : (uid != '0' ? 1 : 0)
              })


              that.getNavadv()
              that.homepageguide();

            } else {
              if (!app.is_auth()) {
                if (app.globalData.is_over_login==false){
                  var pages = getCurrentPages() //获取加载的页面
                  var currentPage = pages[pages.length-1] //获取当前页面的对象
                  var url = currentPage.route //当前页面ur
                  let options = this.data.options
                  options.redirect_url=url

                  let param=decodeURIComponent(options.scene)

                //  delete options.scene

                  let param_query = jsonParamToQueryStr(options)


                  /* 1. 分享 url 参数形式
                  if(param_query==''){
                    param_query=decodeURIComponent(param)
                  }else{
                    param_query=param_query+'&'+decodeURIComponent(param)
                  }
*/
                  // 2. 使用 场景,用户uid 形式  

                  // let param= '10006,4'


                  if(param && param.indexOf(',')!=-1){

                    // 场景,用户uid
                     let s_u=param.split(',')
                     let scene=s_u[0]
                     let share_uid=s_u[1]
                     if(!app.globalData.share_uid){
                      app.globalData.share_uid=share_uid
                     }
  
                     if(param_query==''){
                       let share_uid=s_u[1]
                       param_query='share_uid='+share_uid
                     }else{
                       param_query=param_query+'&share_uid='+share_uid
                     }
                     
                  }

                  console.log('=====end param query: ',param_query)
                  log.info('=====end param query: ',param_query)


                 /* if(options && options.scene){
                    const scene = decodeURIComponent(options.scene)

                    console.log('====onShow scene:',scene)
                    if(scene.length()>0){
                      param_query=param_query+'&'+scene
                    }
                    
                  }*/

                  wx.navigateTo({
                    url: '/pages/login/login?' +param_query,
                  })
                }
               
              }
            }

            that.home();
            wx.hideLoading();
          } else {
            console.error(result);
          }
        },
        fail: err => {
          console.log(err);
        },
      });
    }
  },
  async trailer(e){
	  console.log(e.detail);
	  if(this.data.detail==e.detail){
		  return;
	  }
	  this.setData({
		  detail:e.detail
	  });
	  if(e.detail==1){
		  let page_index= Math.floor(Math.random()*5 + 1) // 1-5页
		  console.log(page_index);
		  let liveData = await pindao({ elite_id: 130, page_index: page_index, page_size: 4 })
		  await setData('liveData', liveData)
		  console.log(liveData);
		  if (liveData && liveData.data) {
		    // liveData.data.forEach(item => {
		    //   item.is_show = true
        // })
        
        for(var i=0;i<liveData.data.length;i++){
          var item=liveData.data[i]
          liveData.data[i].is_show=true
          if(item.video_cover_img==""){
            let videgif=getVideoGifUrl(item.video_info_low.play_url,item.p,item.item_id)
            console.log('------video gif:',videgif)
            liveData.data[i].video_cover_img =videgif
          }

      }
		  }
		  
		  if (liveData.data){
		  
		    if (liveData.data.length%2!=0){
		      // delete liveData.data[liveData.data.length-1] //删除最后一个
		      liveData.data.pop()
		    }
		  }
		  
		  this.setData({
		    liveList: liveData.data ? liveData.data : [],
		  })
	  }else{
		  let page_index= Math.floor(Math.random()*5 + 5) // 1-5页
		  console.log(page_index);
		  let liveData = await pindao({ elite_id: 130, page_index: page_index, page_size: 4 })
		  await setData('liveData', liveData)
		  console.log(liveData);
		  if (liveData && liveData.data) {
		    // liveData.data.forEach(item => {
		    //   item.is_show = true
        // })
        

        for(var i=0;i<liveData.data.length;i++){
          var item=liveData.data[i]
          liveData.data[i].is_show=true
          if(item.video_cover_img==""){
            let videgif=getVideoGifUrl(item.video_info_low.play_url,item.p,item.item_id)
            console.log('------video gif:',videgif)
            liveData.data[i].video_cover_img =videgif
          }

        }
		  }
		  
		  if (liveData.data){
		  
		    if (liveData.data.length%2!=0){
		      // delete liveData.data[liveData.data.length-1] //删除最后一个
		      liveData.data.pop()
		    }
		  }
		  
		  this.setData({
		    liveList: liveData.data ? liveData.data : [],
		  })
	  }
	  
  },
  clipboardProcess:function(){

    console.log('------- clipboardProcess..')
   let that=this
  

    wx.getClipboardData({
      success(res) {
        //var result1 = clipboard.limit(res.data)
        var result1 = res.data

        console.log('剪切板内容:'+result1);

          	//var copy="4fu置内容￥gSM8cf4k5om￥打開绹..寶或点几炼接 https://m.tb.cn/h.VzTQHid 至瀏lan嘂.."; https://u.jd.com/vhrC1r
      
        // var JD= /^https:\/\/u.jd.com\/[\w]{6}$/
        // var VIP=/^https:\/\/t.vip.com\/[\w]{11}\?{1}chanTag=[\w]+$/;
        // var PDD=/^https:\/\/p.pinduoduo.com\/[\w]{8}$/;
        // var TB=/^￥[\w]+￥$/;  //|https:\/\/m.tb.cn\/h.{\w}{7}
        
        var JD= new RegExp(/https:\/\/u.jd.com\/[\w]{6}/,'g')
        var VIP=new RegExp(/https:\/\/t.vip.com\/[\w]{11}\?{1}chanTag=[\w]/,'g');
        var PDD=new RegExp(/https:\/\/p.pinduoduo.com\/[\w]{8}/,'g');
        //var TB=new RegExp(/￥[\w]+￥/,'g'); //|https:\/\/m.tb.cn\/h.{\w}{7}
        var TB=new RegExp(/￥[\w]+￥|￥[\w]+\$|\/[\w]+/,'g'); //|https:\/\/m.tb.cn\/h.{\w}{7}
        
		
        //console.log(TB.test(copy));
        
        let is_jd=JD.test(result1)
        let is_vip=VIP.test(result1)
        let is_pdd=PDD.test(result1)
        let is_tb=TB.test(result1)

        console.log("JD:"+is_jd)
        console.log("VIP:"+ is_vip)
        console.log("PDD:"+ is_pdd)
        console.log("TB:"+ is_tb)



        if(is_jd || is_vip || is_pdd || is_tb){
          // if(JD.test(result1) || VIP.test(result1) || PDD.test(result1) || TB.test(result1)){
          console.log('转链内容')
          if(app.globalData.copyData != result1){
            app.globalData.copyData = result1
            that.setData({
              chain:true,
              copyData:result1,
            })
           

          }
          return 
        }



        if (result1.length > 5 && app.globalData.copyData != result1) {
          app.globalData.copyData = result1
          that.setData({
            is_show_big: 1,
            copyData: result1
          })

        
        }
      }
    })
	


  },
  go_convertlink(){
	  console.log(this.data.copyData);
    var copy=this.data.copyData;
    
    this.setData({
      chain:false
    })
	  wx.navigateTo({
	    url: '/packageTab/pages/turnthe/turnthe?content='+encodeURIComponent(copy),
    })
    

  },
   bindScroll(e) {
      this.setData({
        slideLeft: e.detail.scrollLeft*0.4
      })
    },
  async loadConfigs(){
    // 该接口调用一定要成功，如果失败，那么导致配置缺失 需要通过 index.onShow弥补
    console.log('====loadConfigs')
     let {data} =  await paramGet({param_keys:app.globalData.configs_keys})
     app.globalData.configs = data

      this.calTgCount()
  },
  calTgCount:function(){
    // 设置推广数量
    let tg_share_num=0
    if(!app.globalData.configs.tg_share_num){
      tg_share_num=65378
      app.globalData.configs.tg_share_num=tg_share_num
    }else{
      tg_share_num= app.globalData.configs.tg_share_num+ Math.floor(Math.random()*10 + 1) // 1-10
      app.globalData.configs.tg_share_num=tg_share_num
    }
    this.setData({
      tg_share_num:tg_share_num
    })

  },
  loadLiveData: async function(){
     // 直播记录数据; 默认获取最新的正在直播-即将直播-回放的记录
     const { data } = await getLiveList({ t: 'FX', page_index: 1, page_size: 2 ,is_load_goods:'1'})

 
     this.setData({
      liveDataList: data
     })
     console.log(this.data.liveDataList)


  },

  onHide: function () {
    this.setData({
      showRedPack: 0
    })
  },
  onGetUserInfo: async function ({ detail: { errMsg, userInfo, encryptedData, iv, code, parent_openid } }) {
    const { data } = await getUserData(encryptedData, iv, code, parent_openid,'');
    await setData(dataKey.userInfo, data)
    app.globalData.userInfo = data;
    await setData(dataKey.uid, data.uid)
    app.globalData.uid = data.uid;
    await setData(dataKey.session_key, data.session_key);
    app.globalData.session_key = data.session_key
    await setData(dataKey.token, data.access_token);
    // app.globalData.token = data.access_token
    wx.setStorageSync('token', data.access_token)
  },
  onPullDownRefresh: async function () {
    wx.showNavigationBarLoading();
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
    }, 500);
    await removeData('recommendData')
    await removeData('tip_banner')
    await removeData('top_banner')
    this.home()
  },
  onReachBottom: async function () {
    var that = this;
    if (!this.canLoadMore || this.data.is_load) return;
    this.setData({
      is_load: true
    })
    if (this.data.tabData1[this.data.tabCur1].isAll) {
      let { data } = await search({ q: this.data.tabData1[this.data.tabCur1].name, p: '', price_from: '0', price_to: '9.9', page_index: this.data.tabData1[this.data.tabCur1].pro_page + 1, page_size: 20 })
      let arr = data;
	  
      if (arr!=null && arr.length > 0) {
        // this.data.tabData1[this.data.tabCur1].productList = [...this.data.tabData1[this.data.tabCur1].productList,...arr];
        this.data.tabData1[this.data.tabCur1].pro_page++
        // this.setData({
        //   tabData1:this.data.tabData1,
        // })
        this.setData({
          is_load: false,
          productList: [...this.data.productList, ...arr],
        })
      } else {
        this.setData({
          is_load: false,
        })
        this.canLoadMore = false;
      }
      wx.hideLoading();
      return;
    }
    let c_data;
    if (this.data.tabData1[this.data.tabCur1].p == 'PDD') {
      c_data = await pddPindao({ elite_id: this.data.tabData1[this.data.tabCur1].id, page_index: this.data.tabData1[this.data.tabCur1].pro_page + 1, page_size: 10 })
    } else if (this.data.tabData1[this.data.tabCur1].p == 'JD') {
      c_data = await pindao({ elite_id: this.data.tabData1[this.data.tabCur1].id, page_index: this.data.tabData1[this.data.tabCur1].pro_page + 1, page_size: 10 })
    } else if (this.data.tabData1[this.data.tabCur1].p == 'RE') {
      c_data = await recommend({ page_index: this.data.tabData1[this.data.tabCur1].pro_page + 1, page_size: 30 })
    }



    let arr = c_data.data;
    if (arr!=null &&arr.length > 0) {
      // this.data.tabData1[this.data.tabCur1].productList = [...this.data.tabData1[this.data.tabCur1].productList,...arr];
      this.data.tabData1[this.data.tabCur1].pro_page++
      // this.setData({
      //   tabData1:this.data.tabData1,
      // })
      this.setData({
        is_load: false,
        productList: [...this.data.productList, ...arr],
      })
    } else {
      this.setData({
        is_load: false,
      })
      this.canLoadMore = false;
    }
    wx.hideLoading();
  },
  onShareAppMessage: function () {
    if(!app.is_auth()){
      wx.showToast({
        title: '您还未登陆，请登陆后再分享可以赚佣金哦',
      })
    }
    return shareFun.shareIndex(app.globalData.userInfo.uid,app.globalData.userInfo.wx_nickname);
  },

  async home() {
    var that = this;
    var timestamp = Date.parse(new Date());

    try {
      var indexTime = await getData('indexTime') || timestamp
      if (timestamp - indexTime >= 60 * 60 * 1000) { //超时
        await removeData('recommendData')
        await removeData('tip_banner')
        await removeData('top_banner')
      }


      var recommendData = await getData('recommendData') || {}
      var tip_banner = await getData('tip_banner') || {}
      var top_banner = await getData('top_banner') || {}


    } catch (error) {

    }


    if (!recommendData) {
      // this.getPindao(timestamp);
      this.getRecommend(timestamp);
    } else {
      this.setData({
        productList: recommendData.data,
        show: 1
      }, () => {
        if (that.data.menuTop) return;
        const query = wx.createSelectorQuery();
        query.select('.products').boundingClientRect();
        query.exec((res) => {
          that.setData({
            menuTop: res[0].top - app.globalData.CustomBar,
            menuHeight: res[0].height,
            tab_wrap_top: app.globalData.CustomBar
          })
        });
      })
    }

    //update by finder 20200807
    if (this.is_first_open) {
      this.is_first_open = false;
      //this.getNavadv();
      // this.getBanner();
    }

    this.canLoadMore = true;

    // this.data.tabData1[this.data.tabCur1].productList = recommendData.data
    this.setData({
      height: app.globalData.screenHeight - app.globalData.CustomBar - app.globalData.screenWidth / 750 * 88,
      tabData1: this.data.tabData1,
    })
  },
  moon(){
	  wx.navigateTo({
	    url: '/packageTab/pages/turnthe/turnthe',
	  })
  },
  ducat(e){
	  console.log(e);
	  var p=e.currentTarget.dataset.id.p;
	  var id=e.currentTarget.dataset.id.item_id;
	  var index = e.currentTarget.dataset.index;
	  app.globalData.cur_product = this.data.hot_items[index];
	  wx.navigateTo({
	      url: '/pages/module/productDetail/productDetail?id=' + id + '&p=' + p,
	  })
  },
  async getShortLiveData() { // 获得短视频数据


    let page_index= Math.floor(Math.random()*5 + 1) // 1-5页

    let liveData = await pindao({ elite_id: 130, page_index: page_index, page_size: 4 })
    await setData('liveData', liveData)
	  console.log(liveData);
    if (liveData && liveData.data) {
      // liveData.data.forEach(item => {
      //   item.is_show = true;
      //   if(!item.video_cover_img){
      //     item.video_cover_img =videoGifGet(app.globalData.is_test,item.video_info_low.play_url,item.p,item.item_id)
      //   }
      // })

      for(var i=0;i<liveData.data.length;i++){
          var item=liveData.data[i]
          liveData.data[i].is_show=true
          if(item.video_cover_img==""){
            let videgif=getVideoGifUrl(app.globalData.is_test,item.video_info_low.play_url,item.p,item.item_id)
            console.log('------video gif:',videgif)
            liveData.data[i].video_cover_img =videgif
          }

      }
    }

    if (liveData.data){

      if (liveData.data.length%2!=0){
        // delete liveData.data[liveData.data.length-1] //删除最后一个
        liveData.data.pop()
      }
    }

    this.setData({
      liveList: liveData.data ? liveData.data : [],
    })
	console.log(this.data.liveList);

  },
  async getPindao(timestamp) {
    var that = this;
    this.setData({
      is_load: true
    })

    await setData('indexTime', timestamp)
    // let recommendData = await pindao({elite_id:23,page_index:1,page_size:10})
    let recommendData = await recommend({ page_index: 1, page_size: 20 })
    if(recommendData.data!=null){
      await setData('recommendData', recommendData)
    }
    
    this.setData({
      is_load: false,
      productList: recommendData.data,
      show: 1
    }, () => {
      if (that.data.menuTop) return;
      const query = wx.createSelectorQuery();
      query.select('.products').boundingClientRect();
      query.exec((res) => {
        that.setData({
          menuTop: res[0].top - app.globalData.CustomBar,
          menuHeight: res[0].height,
          tab_wrap_top: app.globalData.CustomBar
        })
      });
    })
    wx.hideLoading({})
  },
  async getRecommend(timestamp) {
    var that = this;
    this.setData({
      is_load: true
    })

    await setData('indexTime', timestamp)
    let recommendData = await recommend({ page_index: 1, page_size: 20 })
    await setData('recommendData', recommendData)
    this.setData({
      is_load: false,
      productList: recommendData.data,
      show: 1
    }, () => {
      if (that.data.menuTop) return;
      const query = wx.createSelectorQuery();
      query.select('.products').boundingClientRect();
      query.exec((res) => {
        that.setData({
          menuTop: res[0].top - app.globalData.CustomBar,
          menuHeight: res[0].height,
          tab_wrap_top: app.globalData.CustomBar
        })
      });
    })
    wx.hideLoading({})
  },
  async getBanner() {
    let top_banner = await getBanner({ group_code: 'banner' });
    await setData('top_banner', top_banner)
    // var swiper = {url:"/images/index/swiper.png",name:'swiper'}
    //var swiper = {url:this.data.img_list.swiper,name:'swiper'}
    top_banner.data = (top_banner.data[0] ? top_banner.data : []);
    // top_banner.data.push(swiper) 
    this.setData({
      carousel: top_banner.data,
    })
	console.log(this.data.carousel);
  },
  async getNavadv() { //授权后调用

    if(app.is_auth()){
      let tip_banner = await getBanner({ group_code: 'navadv' });
      this.setData({
        is_show_active: tip_banner && tip_banner.data && tip_banner.data[0] ? 1 : 0,
        active: tip_banner && tip_banner.data && tip_banner.data[0] ? tip_banner.data[0] : {},
      })
    }
   
  },
  
  async homepageguide() {

    if(app.is_auth()){
      let guide_opts = await getBanner({ group_code: 'guide_idx' });
      if(guide_opts.data=='' || guide_opts.data==[]){
        this.setData({
          guide:0
        })

      }else{
         //var result=top_banner.data[0].extras.split(",");
        this.setData({
          guide:guide_opts && guide_opts.data && guide_opts.data[0] ? 1 : 0,
          guide_opt:guide_opts && guide_opts.data && guide_opts.data[0]?guide_opts.data[0]:{}
        })
       
      }

     
  	}
	
  },
  
  goSearch(e) {
    var key = e.currentTarget.dataset.key
    var p = e.currentTarget.dataset.p
    var tabIndex = e.currentTarget.dataset.tabindex
    var cf = e.currentTarget.dataset.cf
    var ct = e.currentTarget.dataset.ct
    var zf = e.currentTarget.dataset.zf
    var zt = e.currentTarget.dataset.zt
    var pf=e.currentTarget.dataset.pf
    var pt=e.currentTarget.dataset.pt

    pf=pf?pf:''
    pt=pt?pt:''


	console.log(e);
    wx.navigateTo({
      url: '/pages/module/search/searchResult/searchResult?tabIndex=' + tabIndex + "&keyword=" + key + '&commission_rate_from=' + cf + '&commission_rate_to=' + ct + '&p=' + p + '&zk_rate_from=' + zf + '&zk_rate_to=' + zt+'&price_from='+pf+'&price_to='+pt,
    })
  },
 //  goCar() { 
	// wx.navigateTo({
	//   url: '/packageTab/pages/ticket/ticket',
	// })
 //  },
 //  goMobile() {
	// wx.navigateTo({
	//   url: '/packageTab/pages/phone/phone',
	// })
 //  },
  async swiperChange1(e) {
    if (this.data.tabCur1 == e.detail.current) return;
    if (this.data.tabData1[e.detail.current] && this.data.tabData1[e.detail.current].productList && this.data.tabData1[e.detail.current].productList.length > 0) {
      return;
    } else {
      this.data.tabData1[e.detail.current].productList = this.data.tabData1[this.data.tabCur1].productList;
    }
    this.setData({
      tabCur1: e.detail.current,
    })
    this.canLoadMore = true;
    const { data } = await recommend({
      elite_id: this.data.tabData1[e.detail.current].id,
      page_size: 10
    })
    this.data.tabData1[e.detail.current].productList = data;
    this.setData({
      tabData1: this.data.tabData1
    })
  },
  async tabChange(e) {
    if (this.scrollTop >= this.data.menuTop) {
      wx.pageScrollTo({
        scrollTop: this.data.menuTop,
      })
    }
    if (this.data.tabCur1 == e.detail.index) return;
    this.setData({
      tabCur1: e.detail.index,
    })
    // if(this.data.tabData1[e.detail.index]&&this.data.tabData1[e.detail.index].productList&&this.data.tabData1[e.detail.index].productList.length>0){
    //   return;
    // } else {
    //   this.data.tabData1[e.detail.index].productList = this.data.tabData1[this.data.tabCur1].productList;
    // }
    this.data.tabData1[this.data.tabCur1].pro_page = 1
    this.canLoadMore = true;
    if (this.data.tabData1[e.detail.index].isAll) {
      let { data } = await search({ q: '', p: '', price_from: '0', price_to: '9.9', page_index: this.data.tabData1[this.data.tabCur1].pro_page, page_size: 20 })
      this.setData({
        productList: data,
      })
      return;
    }
    let c_data;
    if (this.data.tabData1[e.detail.index].p == 'PDD') {
      c_data = await pddPindao({
        elite_id: this.data.tabData1[e.detail.index].id,
        page_size: 10
      })
    } else if (this.data.tabData1[e.detail.index].p == 'JD') {
      c_data = await pindao({
        elite_id: this.data.tabData1[e.detail.index].id,
        page_size: 10
      })
    } else if (this.data.tabData1[e.detail.index].p == 'RE') {
      c_data = await recommend({

        page_size: 30
      })
    }

    // this.data.tabData1[e.detail.index].productList = data;
    // this.setData({
    //   tabData1:this.data.tabData1
    // })
    this.setData({
      productList: c_data.data,
    })
  },
  async select(e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    this.data.select_list.forEach(item => {
      item.is_select = 0
    })
    this.data.select_list[index].is_select = 1
    this.setData({
      select_list: this.data.select_list,
      showMenu: 0
    })
    const { data } = await refreshInfo({ uid: app.globalData.uid, identity_status: this.data.select_list[index].status })
  },
  //分类
  goClassification() {
    wx.navigateTo({
      url: '/pages/module/classification/classification',
    })
  },
  async chooseP(e) {
    var p = e.currentTarget.dataset.p
    var index = e.currentTarget.dataset.index
    var keyword = this.data.copyData
    this.setData({
      is_show_big: 0
    })
    wx.navigateTo({
      url: '/pages/module/search/searchResult/searchResult?keyword=' + keyword + '&p=' + p + '&tabIndex=' + index
    })
  },
  swiperChange(e) {
	  var that=this;
    that.setData({
      currentIndicator: e.detail.current
    })
  },
  activeSwiperChange(e) {
    this.setData({
      cur_index: e.detail.current
    })
  },
  search() {
    wx.navigateTo({
      url: '/pages/module/search/search',
    })
  },
  closeDown() {
    this.setData({
      is_show_big: 0,
      is_show_active: 0,
    })
  },
  closeDownChain(){
    this.setData({
      chain:false
    })
  },
  async closeDown1() {
    this.setData({
      is_show_active: 0,
    })
  },
  productDetail(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/module/productDetail/productDetail?id=' + id
    })
  },
  async load_approve_mod() { //加载审核模式

    console.log("version:", app.globalData.version)
    let { data } = await approve_mode({ code: app.globalData.version })


    app.globalData.is_audit = data == 0 ? false : true

    console.log("====is_audit:", app.globalData.is_audit)
    setTabList.call(this, 1, !app.globalData.is_audit)


    this.setData({
      is_audit:app.globalData.is_audit
    })

    if(!this.data.is_audit){
      this.loadLiveData() //加载直播数据,这个数据可能有状态数据改变
    }

  },
  mdds(){
  	  wx.navigateTo({
  	    url: '/packageTab/pages/promote/promote',
  	  })
  },
  navigate(e) {
  
    var url = e.currentTarget.dataset.url;
    var app_id = e.currentTarget.dataset.id;
    var nav_type = e.currentTarget.dataset.out;
	var index=e.currentTarget.dataset.index;
	console.log(e);
	console.log(url);
    if (!url) {
      return;
    }
    if (nav_type == 'weapp') {
      wx.navigateToMiniProgram({
        appId: app_id,
        path: url
      })
    } else if (nav_type == "weappin") {
      // 内部路径导航
      wx.navigateTo({
        url: url,
      })

    }else if (nav_type == 'h5') {
      wx.navigateTo({
        url: '/pages/common/h5/webview/webview?url=' + url
      })
    }
  },
  async navigate1(e) {
	console.log(e.currentTarget.dataset.url)
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.id;
     //if (id == '1' || id == '2') {
      if (!app.is_auth()) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return;
    } else if (id == '0') {
      wx.navigateTo({
        url: '/pages/module/search/searchResult/searchResult?tabIndex=' + '0' + "&keyword=" + '' + '&price_from=' + '0' + '&price_to=' + '2.0',
      })
      return;
    }
	else if(id=='4'){
		const {
			data
		} = await checkHostReg();
		console.log(data);
		if(data==3){
			wx.navigateTo({
			  url: '/pages/module/liveManagement/liveManagement'
			})
		}else{
			wx.navigateTo({
			  url: '/pages/module/hostApply/hostApply'
			})
		}
		return;
	}
	// else if(id=='1'){
	// 	wx.navigateToMiniProgram({
	// 	  appId:'wx32540bd863b27570',
	// 	  path:'/pages/web/web?specialUrl=1&src=https%3A%2F%2Fmobile.yangkeduo.com%2Fduo_transfer_channel.html%3FresourceType%3D39996%26pid%3D10530160_142298714%26_pdd_fs%3D1%26_pdd_tc%3Dffffff%26_pdd_sbs%3D1%26customParameters%3Dtrue%26cpsSign%3DCE_200723_10530160_142298714_5e6e4f4e82c2c32a32c7a0397796d971%26duoduo_type%3D2'
	// 	})
	// 	return;
	// }
	// else if(id=='2'){
	// 	wx.navigateToMiniProgram({
	// 	  appId:'wx32540bd863b27570',
	// 	  path:'/pages/web/web?specialUrl=1&src=https%3A%2F%2Fmobile.yangkeduo.com%2Fduo_transfer_channel.html%3FresourceType%3D4%26pid%3D10530160_142298714%26customParameters%3Dtrue%26cpsSign%3DCE_200723_10530160_142298714_b522322ce22af5fb81dc6e01230817c2%26duoduo_type%3D2'
	// 	})
	// 	return;
	// }
    wx.navigateTo({
      url: url
    })
  },
  async navigate2(e) {
    this.setData({
      is_show_active: 0
    })
    if (this.data.active.nav_type == "weapp") {
      wx.navigateToMiniProgram({
        appId: this.data.active.app_id,
        path: this.data.active.link_url,
      })
    } else if (this.data.active.nav_type == "weappin") {
      // 内部路径导航
      wx.navigateTo({
        url: this.data.active.link_url,
      })

    } else {
      wx.navigateTo({
        url: '/pages/common/h5/webview/webview?url=' + url
      })
    }
    await saveRecord({ user_id: app.globalData.uid, adv_id: this.data.active.id });
  },
  switchTab(e) {
    var url = e.currentTarget.dataset.url;
    if (!url) {
      return;
    }
    wx.switchTab({
      url: url
    })
  },
  shopCar() {
    wx.navigateTo({
      url: '/pages/module/shopCar/shopCar',
    })
  },
})